package PriorityQueue;

import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }
    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void createHeap(){
        for (int parent = (usedSize-1-1)/2; parent >= 0 ; parent--) { // 根节点都是大于等于0
            shiftDown(parent,usedSize);
        }
    }
    /**
     * @param parent 父亲下标
     * @param len 每棵树的结束下标
     * @return void
     * @description 向下调整
     */
    private void shiftDown(int parent,int len){
        int child = 2*parent +1;
        while(child<len){ //最起码要有左孩子
            //一定有 右孩子 的情况下：  child+1 <len
            if(child+1 <len && elem[child] < elem[child+1]){
                child++; //满足 child 下标一定是左右孩子的最大下标
            }
            //交换
            if(elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = child = 2*parent +1;
            }else{
                break;
            }
        }
    }
/**
 * @param val
 * @description 插入元素
 */
    public void offer(int val){
        if(isFull()){//扩容
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = val;//11
        shiftUp(usedSize-1);
    }
    public boolean isFull(){
        return usedSize == elem.length;
    }
/**
 * @param child
 * @description 向上调整
 */
    private void shiftUp(int child){
        int parent = (child-1)/2;
        while (child > 0){
            if(elem[child] >elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1)/2;
            }else{
                break;
            }
        }
    }
    public void poll(){
        if(isEmpty()){
            return;
        }
        swap(elem,0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }
    public boolean isEmpty(){
        return usedSize==0;
    }

    private void swap(int[] array,int i,int j){
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }

/**
 * @param
 * @description 时间复杂度：O(n*logN)
 *              空间复杂度：O(1)
 */
    public void heapSort(){
        int end = usedSize-1;
        while(end > 0){
            swap(elem,0,end);
            shiftDown(0,end);
            end--;
        }
    }
}
